#include "System.h"
using namespace yazi::utility;

#include "Logger.h"
#include "Singleton.h"
#include "IniFile.h"
using namespace yazi::utility;

#include "WorkFlow.h"
using namespace yazi::engine;

#include <unistd.h>
#include <cstring>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <dirent.h>



System::System() : m_root_path(""){

}

System::~System(){

}

void System::init(){
    core_dump();
    m_root_path = get_root_path();

    const string& logdir = m_root_path + "/log";
    DIR* dp = opendir(logdir.c_str());
    if(dp == NULL)
        mkdir(logdir.c_str(), 0755);
    else closedir(dp);
    Logger::instance()->open(m_root_path + "/../log/main.log");

    Singleton<IniFile>::instance()->load(get_root_path() + "/../config/main.ini");
    //init workflow
    WorkFlow * workflow = Singleton<WorkFlow>::instance();
    workflow->load(get_root_path() + "/../config/workflow.xml");
    info("workflow load successfully");
}

string System::get_root_path(){
    if(m_root_path != "")
        return m_root_path;
    char buf[1024];
    memset(buf, 0, sizeof buf);
    int len = readlink("/proc/self/exe", buf, 1024);
    if(len < 0 || len >= 1024){
        error("System::get_root_path() error, len = %d", len);
        return "";
    }
    for(int i = len; i >= 0; --i){
        if(buf[i] == '/'){
            buf[i] = '\0';
            break;
        }
    }
    debug("System::get_root_path():, path = %s", buf);
    return (string)buf;
}

void System::core_dump(){
    struct rlimit x;
    int ret = getrlimit(RLIMIT_CORE, &x);
    x.rlim_cur = x.rlim_max;
    ret = setrlimit(RLIMIT_CORE, &x);

    ret = getrlimit(RLIMIT_DATA, &x);
    x.rlim_cur = 768000000;
    ret = setrlimit(RLIMIT_DATA, &x);
}